//
//  WNStoreVC.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/7.
//

import UIKit
import SwiftyStoreKit
import KeychainAccess

let itemWidth = (ScreenW-45)*0.5
let itemHeight = itemWidth*0.61+40

class WNStoreVC: WNBaseVC {
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: WNNotiName.rechargeNoti, object: nil)
    }
    
    lazy var storeColView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 15
        layout.minimumInteritemSpacing = 15
        layout.itemSize = CGSize(width: itemWidth, height: itemHeight)
        layout.sectionInset = UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15)
        let col = UICollectionView.init(frame: .zero, collectionViewLayout: layout)
        col.showsVerticalScrollIndicator = false
        col.showsHorizontalScrollIndicator = false
        col.backgroundColor = .white
        col.delegate = self
        col.dataSource = self
        col.register(StoreColCell.self, forCellWithReuseIdentifier: StoreColCell.identifier)
        return col
    }()
    
    lazy var agreementView: IQTextView = {
        let view = IQTextView()
        view.font = .wn_font(name: .bold, size: 13)
        view.showsVerticalScrollIndicator = false
        view.wn_appendLinkString(string: "需要幫助嗎？請訪問我們的")
        view.wn_appendLinkString(string: " 問與回答 ", withURLString: WNConfigure.WNURL.wn_Contact)
//        view.wn_appendLinkString(string: "or")
//        view.wn_appendLinkString(string: " Restore Purchase", withURLString: "https://Restore")
        view.textColor = .init(named: "gray_999999")
        view.linkTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.black, NSAttributedString.Key.font: UIFont.wn_font(name: .bold, size: 13)]
        view.isEditable = false
        view.isScrollEnabled = false
        view.delegate = self
        view.contentInset = .init(top: -10, left: -5, bottom: 0, right: 0)
        return view
    }()
    
    lazy var tipsLabel: UILabel = {
        let label = UILabel()
        label.text = "為了保護您在「最嗨小说」上的數位資產，我們建議使用 Apple 帳戶登入時購買金幣。"
        label.textColor = .init(named: "gray_999999")
        label.font = .wn_font(name: .bold, size: 11)
        label.numberOfLines = 0
        return label
    }()
    
    var rechargeArr = [RechargeDetailModel]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewConfig() {
        view.addSubview(tipsLabel)
        view.addSubview(agreementView)
        view.addSubview(storeColView)
        tipsLabel.snp.makeConstraints { (make) in
            make.bottom.equalTo(-TabBarTotalHeight)
            make.left.equalTo(15)
            make.right.equalTo(-15)
        }
        agreementView.snp.makeConstraints { (make) in
            make.bottom.equalTo(tipsLabel.snp.top).offset(-12)
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.size.equalTo(CGSize.init(width: 160, height: 15))
        }
        storeColView.snp.makeConstraints { make in
            make.top.equalTo(NaviTotalHeight+12)
            make.left.right.equalTo(0)
            make.bottom.equalTo(agreementView.snp.top).offset(-12)
        }
    }
    
    override func dataConfig() {
        pageName = "商店"
        navView.titleName = "商店"
        getRechargeList()
    }
    
    override func handleNoti() {
        NotificationCenter.default.addObserver(forName: WNNotiName.rechargeNoti, object: nil, queue: nil) { [weak self] not in
            self?.getRechargeList()
        }
    }
}

extension WNStoreVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UITextViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        rechargeArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: StoreColCell.identifier, for: indexPath) as! StoreColCell
        cell.tag = indexPath.item+1
        cell.model = rechargeArr[indexPath.item]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        WNBuriedManager.shared.logProductItem(rechargeArr[indexPath.item].productId ?? "", rechargeArr[indexPath.item].productName ?? "", rechargeArr[indexPath.item].price)
        WNPayManager.shared.creatRechargeOrder(rechargeArr[indexPath.item].productId ?? "", rechargeArr[indexPath.item].productName ?? "", rechargeArr[indexPath.item].price)
    }
    
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        if URL.absoluteString == "https://Restore" {
            WNPayManager.shared.restorePurchase()
        }else {
//            wn_pushWebVC(WNConfigure.WNURL.wn_Contact, "聯絡我們")
        }
        return false
    }
}

extension WNStoreVC {
    /// 充值列表
    func getRechargeList() {
        provider_setting.rx.request(.rechargeList)
            .asObservable().mapModel(BaseModel<[RechargeDetailModel]>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    self?.wn_toast(model.msg ?? "")
                    return
                }
                if let arr = model.data {
                    self?.rechargeArr = arr
                    self?.storeColView.reloadData()
                }
            }, onError: { [weak self] (error) in
                self?.wn_toast("檢查網路連線")
            }).disposed(by: rx.disposeBag)
    }
}
